package com.taihe.template.base.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by User on 16/6/22.
 */
public class Downloader {
    public interface Callback{
        void onSuccess();
        void onFail();
    }

    public static void download(final String url, final String filePath, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String suffix = ".tmp";
                FileOutputStream fos = null;
                try {
                    URL u = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                    connection.setReadTimeout(3000);
                    connection.setDoInput(true);
                    connection.setDoOutput(false);
                    connection.setConnectTimeout(10000);
                    InputStream is = connection.getInputStream();
                    File tmpFile = new File(filePath + suffix);
                    fos = new FileOutputStream(tmpFile);
                    byte[] buffer = new byte[2048];
                    int n = 0;
                    do {
                        Thread.yield();
                        fos.write(buffer, 0, n);
                        n = is.read(buffer);
                    } while (n != -1);
                    fos.close();
                    tmpFile.renameTo(new File(filePath));
                    callback.onSuccess();
                } catch (Exception e) {
                    callback.onFail();
                } finally {
                    new File(filePath + suffix).delete();

                }
            }
        }).start();
    }
}
